package edu.ccut.saturn.workflow.common;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.jexl.ExpressionFactory;
import org.apache.commons.jexl.JexlContext;
import org.apache.commons.jexl.JexlHelper;

import edu.ccut.saturn.component.ComponentFactory;
import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.IComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.operation.Operation;
import edu.ccut.saturn.workflow.model.ActivityInfo;
import edu.ccut.saturn.workflow.model.DecisionInfo;
import edu.ccut.saturn.workflow.model.IfInfo;
import edu.ccut.saturn.workflow.model.LogicKeyInfo;
import edu.ccut.saturn.workflow.model.ManInfo;
import edu.ccut.saturn.workflow.model.ParameterInfo;
import edu.ccut.saturn.workflow.model.UserInfo;
import edu.ccut.saturn.workflow.model.WorkFlowInfo;
import edu.ccut.saturn.workflow.startWorkFlowModule.code.IActivateActivity;
import edu.ccut.saturn.workflow.startWorkFlowModule.code.WorkFlowInstanceFactory;

public class WorkFlowTools {

	/**
	 * 获得工作项参与者字符串（aaa|bbb)
	 * 
	 * @param activityInfo
	 * @return
	 */
	//TODO 插入的是参与者的姓名，应该是ID
	public static String getWorkItemParticipant(ActivityInfo activityInfo) {
		String participant = "";
		List<UserInfo> userInfos = activityInfo.getUsers();
		for (int i = 0; i < userInfos.size(); i++) {
			UserInfo userInfo = userInfos.get(i);
			if (i == userInfos.size() - 1) {
				participant = participant + userInfo.getName();
			} else {
				participant = participant + userInfo.getName() + "|";
			}
		}
		return participant;
	}

	/**
	 * 根据id得到user对应的用户中文名
	 * 
	 * @param type
	 * @param id
	 * @param conn
	 * @return
	 * @throws Exception 
	 */
	public static String getUserNameById(String id, Connection conn) throws Exception {
		HashMap<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		ArrayList<SaturnData> users = Operation.dataBase().queryBySaturnSql(Constants.SATURNDATA_WF_SATURN_AUTH_USER, "GET_USERNAME_BY_ID", paramMap, conn);
		if(users!=null){
			return users.get(0).getString("username");
		}
		return "";
	}
	
	/**
	 * 根据类型得到用户列表
	 * 
	 * @param type(角色role,部门department,岗位position,用户user)
	 * @param id(角色id,部门id,岗位id)
	 * @return ArrayList<SaturnData>
	 * @throws Exception 
	 */
	public static ArrayList<SaturnData> getUserDataListByTypeAndId(String type, String id, Connection conn) throws Exception{		
		ArrayList<SaturnData> userDataList = null;
		HashMap<String,Object> paramMap = new HashMap<String,Object>();
		if (Constants.PARTICIPANT_TYPE_ROLE.equals(type)) {
			//根据角色得到用户
			paramMap.put("role_id", id);
			userDataList = Operation.dataBase().queryBySaturnSql(Constants.SATURNDATA_WF_SATURN_AUTH_USER, 
									"GET_USERS_BY_ROLEID", paramMap, conn);
		}else if (Constants.PARTICIPANT_TYPE_DEPARTMENT.equals(type)) {
			///根据部门得到用户
			paramMap.put("dept_id", id);
			userDataList = Operation.dataBase().queryBySaturnSql(Constants.SATURNDATA_WF_SATURN_AUTH_USER, 
									"GET_USERS_BY_DEPARTID", paramMap, conn);
		}
		else if (Constants.PARTICIPANT_TYPE_POSITION.equals(type)) {
			//根据职位得到用户
			paramMap.put("position", id);
			userDataList = Operation.dataBase().queryBySaturnSql(Constants.SATURNDATA_WF_SATURN_AUTH_USER, 
									"GET_USERS_BY_POSITION", paramMap, conn);
		}else if(Constants.PARTICIPANT_TYPE_USER.equals(type)){
			//根据用户id得到用户
			paramMap.put("id", id);
			userDataList = Operation.dataBase().queryBySaturnSql(Constants.SATURNDATA_WF_SATURN_AUTH_USER, 
					"GET_USER_BY_ID", paramMap, conn);
		}
		
		return userDataList;	
	}
	
   /**
    * 执行自定义参与者逻辑,获取自定义参与者
    */
	@SuppressWarnings("unchecked")
	public static List<HashMap<String, String>> executeCustomUserLogic(
			ActivityInfo currentActivityInfo, Map<String,String> workFlowParamMap)
			throws SQLException {
		//取出自定义参与者logic
		LogicKeyInfo customUserLogic = ((ManInfo) currentActivityInfo)
				.getCustomUserLogic();
		String customUserLogicFullkey = null;
		if (customUserLogic != null) {
			//如果存在自定义logic，则取出logic的fullkey
			customUserLogicFullkey = customUserLogic.getFullKey();
		}
		//存在自定义参与者

		String value = null;
		IParameterContext pc = ComponentFactory.createParameterContext();
		List<ParameterInfo> paramList = customUserLogic.getParamList();
		for (int i = 0; i < paramList.size() - 1; i++) {
			value = (String) workFlowParamMap
					.get(((ParameterInfo) paramList.get(i)).getKey());
			pc.addParameter(value, String.class);
		}
		// 最后一个是输出参数
		pc.addParameter(null, ArrayList.class);
		try {
			IComponent component = ComponentManager.getInstance()
					.getComponent(customUserLogicFullkey);
			component.execute(pc);
		} catch (SaturnComponentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pc.hasConnection()) {
				pc.getConnection().close();
			}
		}
		List<HashMap<String, String>> userInfos = (List<HashMap<String, String>>) pc
				.getParameterValue(paramList.size() - 1 );
		return userInfos;
	}
	/**
	 *  @执行参与者交验逻辑
	 */
	public static boolean executeParticipantFilterLogic(String validateuserlogicFullkey,String previousAssistant,
				String userSerialNo,String businessType) throws Exception {
		
		IParameterContext pc = ComponentFactory.createParameterContext();
		// 取得上一步执行者 这里暂时不取多工作项情况，不取多活动前驱的情况，只是一对一

		pc.addParameter(previousAssistant,String.class);// 上一步执行者
		pc.addParameter(userSerialNo, String.class);// 当前期望执行者
		pc.addParameter(businessType, String.class);// 业务类型
		pc.addParameter(null, Boolean.class);
		try {
			IComponent component = ComponentManager.getInstance().getComponent(
					validateuserlogicFullkey);
			component.execute(pc);
		} catch (SaturnComponentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pc.hasConnection()) {
				pc.getConnection().close();
			}
		}
		// 判断是否有效的执行期望者，是则插入参与者表
		boolean isValidUser = (Boolean) pc.getParameterValue(3);
		return isValidUser;
	}
	
	/**
	 * 获得工作项实例对象（为插入工作项实例表用）
	 * 
	 * @param workFlowInstance
	 * @param activityInstance
	 * @param activityInfo
	 * @param workFlowInfo
	 * @param conn
	 * @param user
	 * @return
	 * @throws SQLException
	 * @throws ParseException
	 * @throws NumberFormatException
	 */
	public static SaturnData getWorkItemInstance(SaturnData workFlowInstance,
			SaturnData activityInstance, SaturnData previous_workitem_instance,ActivityInfo activityInfo,
			WorkFlowInfo workFlowInfo, Connection conn)
			throws Exception {
		String systemTime = Operation.baseService().GetSystemTime();
		SaturnData workItemInstance = Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_WORKITEM_INSTANCE);
		workItemInstance.setString("name", activityInfo.getName());
		workItemInstance.setString("type", activityInfo.getType());
		workItemInstance.setString("validateuserlogic", activityInfo
				.getValidateUserLogic());
		workItemInstance
				.setString("description", activityInfo.getDescription());
		workItemInstance.set("state", Constants.WORKITEM_STATE_RUNNING);
	    //TODO 设置participant字段 6.12
		/*String getUserType = ((ManInfo)activityInfo).getObtainFromActivityRadioButton();
		if(Constants.OBTAINFROMACTIVITYRADIOBUTTON_ACTIVITY.equals(getUserType)){
			workItemInstance.setString("participant",workFlowInfo.getActivityInfoById(activityInfo.getUserFrom()).getName());
		}else if(Constants.OBTAINFROMACTIVITYRADIOBUTTON_CUSTOM.equals(getUserType)){
			workItemInstance.setString("participant", "CUSTOM PARTICIPANT");
		}else if(Constants.OBTAINFROMACTIVITYRADIOBUTTON_START.equals(getUserType)){
			workItemInstance.setString("participant", workFlowInstance.get("creator_name")+ "");
		}else if(Constants.OBTAINFROMACTIVITYRADIOBUTTON_COMMON.equals(getUserType)){
			workItemInstance.setString("participant", getWorkItemParticipant(activityInfo));
		}*/
		workItemInstance.set("priority", 80);//工作项暂无优先级功能。工作流实例上有，标识工作流的紧急等级
		if (activityInfo.getTimeLimit() != null
				&& !"".equals(activityInfo.getTimeLimit())) {
			workItemInstance.set("limit_number", Integer.parseInt(activityInfo
					.getTimeLimit()));
			workItemInstance.set("final_time", getTimeWithInterval(systemTime,
					Long.parseLong(activityInfo.getTimeLimit())));
		} else {
			workItemInstance.set("limit_number", 0);
		}
		workItemInstance.setString("create_time", systemTime);
		workItemInstance.setString("start_time", systemTime);
		workItemInstance.setString("action_key", activityInfo.getUrl());
		workItemInstance.set("process_instance_id", workFlowInstance
				.get("process_instance_id"));
		workItemInstance.set("activity_instance_id", activityInstance
				.get("activity_instance_id"));
		workItemInstance.setString("process_instance_name", workFlowInstance
				.getString("name"));
		workItemInstance.setString("activity_instance_name", activityInstance
				.getString("name"));
		workItemInstance.set("process_define_id", workFlowInstance
				.get("process_define_id"));
		workItemInstance.setString("process_xml_key", workFlowInfo.getKey());
		workItemInstance.setString("process_define_name", workFlowInfo
				.getName());
		workItemInstance.setString("activity_define_id", activityInfo.getId());
		//TODO bizstate
		workItemInstance.setString("bizstate", "0");
		//前一活动为单一前驱，并且非多工作项才有意义
		workItemInstance.setString("previous_assistant", previous_workitem_instance.getString("assistant"));
		workItemInstance.setString("previous_assistant_name",previous_workitem_instance.getString("assistant_name") );
		workItemInstance.setString("previous_assistant_department",
				previous_workitem_instance.getString("assistant_department"));
		
		return workItemInstance;
	}

    /**
     * 获得参与者数据项
     * @throws Exception 
     */
	public static SaturnData getParticipantInstance() throws Exception{
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_WIPARTICIPANT);
	}
	/**
	 * 获得工作项数据项
	 */
	public static SaturnData getWorkItemInstance() throws Exception{
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_WORKITEM_INSTANCE);
	}
	/**
	 * 获得活动数据项
	 */
	public static SaturnData getActivityInstance() throws Exception{
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_ACTIVITY_INSTANCE);
	}
	/**
	 * 获得工作流实例数据项
	 */
	public static SaturnData getProcessInstance() throws Exception {
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_PROCESS_INSTANCE);
	}
	/**
	 * 获得工作流定义数据项
	 */
	public static SaturnData getProcessDefineInstance() throws Exception{
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_PROCESS_DEFINE);
	}
	/**
	 * 获得流转路径数据项
	 */
	public static SaturnData getTransitionInstance() throws Exception {
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_TRANSITION);
	}
	/**
	 * 获得代办表数据项
	 */
	public static SaturnData getDelegateInstance() throws Exception {
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_DELEGATE);
	}
	/**
	 * 获得用户数据项
	 */
	public static SaturnData getUserInstance() throws Exception {
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_SATURN_AUTH_USER);
	}
	/**
	 * 获得代理数据项
	 */
	public static SaturnData getAgentInstance() throws Exception {
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_AGENT);
	}
	/**
	 * 获得代理明细数据项
	 */
	public static SaturnData getAgentitemInstance() throws Exception {
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_AGENTITEM);
	}
	/**
	 * 获得代办消息数据项
	 */
	public static SaturnData getDelegateMesgInstance() throws Exception {
		return Operation.baseService().CreateSaturnData(Constants.SATURNDATA_WF_DELEGATE_MESSAGE);
	}
	/**
	 * 获得参与者实例，并付值
	 * @throws Exception 
	 */
	public static SaturnData getParticipantInstanceWithValues( String participant,String participantName) throws Exception{
		SaturnData wiParticipantData = getParticipantInstance();
		wiParticipantData.setString("participanttype", Constants.PARTICIPANT_TYPE_USER);
		wiParticipantData
				.setString("participant", participant);
		wiParticipantData.setString("participant2", participantName);
		return wiParticipantData;
	}

	/**
	 * 判断是否某个活动的前驱活动是否都完成
	 * 
	 * @param workFlowInfo
	 * @param workItemData
	 * @param activityInfo
	 * @param conn
	 * @return
	 * @throws Exception 
	 */
	public static boolean ifBeforeActivityAllFinish(WorkFlowInfo workFlowInfo,
			SaturnData workItemData, ActivityInfo activityInfo, Connection conn) throws Exception {
		boolean flag = false;
		int finishNum = 0;
		ArrayList<ActivityInfo> activityInfoList = workFlowInfo
				.getBeforeActivityByActId(// 得到包括路由在内的节点
				activityInfo.getId());
		String process_instance_id = workItemData.get("process_instance_id")
				+ "";
		for (int i = 0; i < activityInfoList.size(); i++) {
			ActivityInfo activityInfoP = activityInfoList.get(i);
			String activityDefId = activityInfoP.getId();
			if (getActivityStateByPidAndAdefId(process_instance_id,
					activityDefId, conn) == Constants.ACTIVITY_STATE_FINISH) {
				finishNum = finishNum + 1;
			}
		}
		if (finishNum == activityInfoList.size()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 判断是否某个活动的前驱活动（不包括路由活动）是否都完成
	 * 
	 * @param workFlowInfo
	 * @param workItemData
	 * @param activityInfo
	 * @param conn
	 * @return
	 * @throws Exception 
	 */
	public static boolean ifBeforeActivityAllFinishWithoutDesition(
			WorkFlowInfo workFlowInfo, SaturnData workItemData,
			ActivityInfo activityInfo, Connection conn) throws Exception {
		boolean flag = false;
		int finishNum = 0;
		ArrayList<ActivityInfo> activityInfoList = workFlowInfo
				.getBeforeActivityWithoutDecision(// 不包括路由在内的节点
				activityInfo.getId());
		String process_instance_id = workItemData.get("process_instance_id")
				+ "";
		for (int i = 0; i < activityInfoList.size(); i++) {
			ActivityInfo activityInfoP = activityInfoList.get(i);
			String activityDefId = activityInfoP.getId();
			if (getActivityStateByPidAndAdefId(process_instance_id,
					activityDefId, conn) == Constants.ACTIVITY_STATE_FINISH) {
				finishNum = finishNum + 1;
			}
		}
		if (finishNum == activityInfoList.size()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 根据流程实例id和活动定义id获得活动状态
	 * 
	 * @param process_instance_id
	 * @param activityDefId
	 * @param conn
	 * @return
	 * @throws Exception 
	 */
	public static int getActivityStateByPidAndAdefId(
			String process_instance_id, String activityDefId, Connection conn) throws Exception {
		int state = 0;
		HashMap<String,Object> paramMap = new HashMap<String,Object>();
		
		paramMap.put("process_instance_id", process_instance_id);
		paramMap.put("activity_id", activityDefId);
		
		ArrayList<SaturnData> result = Operation.dataBase().queryBySaturnSql(Constants.SATURNDATA_WF_ACTIVITY_INSTANCE, 
						"GET_ACTIVITY_INSTANCE_BY_PROID_AND_ADEFID", paramMap, conn);
		if(result!=null){
			return Integer.parseInt(result.get(0).get("state")+"");
		}
		return state;
	}
	/**
	 * 获得传输路径实例对象（为插入传输路径表用）
	 * 
	 * @param conn
	 * @param beforeActivityInstance
	 * @param activityInstance
	 * @return
	 * @throws SQLException
	 */
	public static SaturnData getTransitionInstance(Connection conn,
			SaturnData beforeActivityInstance, SaturnData activityInstance)
			throws Exception {
		SaturnData transitionInstance = getTransitionInstance();
		transitionInstance.set("transition_type", "V");//没意义
		transitionInstance.set("causeactinst_id", beforeActivityInstance
				.get("activity_instance_id"));
		transitionInstance.set("causeactinst_name", beforeActivityInstance
				.get("name"));
		transitionInstance.set("resultactinst_id", activityInstance
				.get("activity_instance_id"));
		transitionInstance.set("resultactinst_name", activityInstance
				.get("name"));
		transitionInstance.set("srcactdef_id", beforeActivityInstance
				.get("activity_id"));
		transitionInstance.set("srcactdef_name", beforeActivityInstance
				.get("name"));
		transitionInstance.set("destactdef_id", activityInstance
				.get("activity_id"));
		transitionInstance.set("destactdef_name", activityInstance.get("name"));
		transitionInstance.set("transtime", activityInstance.get("start_time"));
		transitionInstance.set("processinst_id", activityInstance
				.get("process_instance_id"));
		return transitionInstance;
	}


	 /**
	 * 根据间隔得到新的时间
	 *
	 * @return
	 */
	 public static String getTimeWithInterval(String sourceTime, Long
	 interval)
	 throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date dateparse = null;
		dateparse = format.parse(sourceTime);
		Long newTime = dateparse.getTime() + interval;
		dateparse.setTime(newTime);
		return format.format(dateparse);
	}
	 /**
	  * 判断并激活活动
	  */
	 @SuppressWarnings("unchecked")
	public static void checkToActivateActivity(
			IParameterContext parameterContext) throws Exception {
		SaturnData workFlowInstance = (SaturnData) parameterContext
				.getParameterValue(0);
		WorkFlowInfo workFlowInfo = (WorkFlowInfo) parameterContext
				.getParameterValue(1);
		Map<String, String> workFlowParamMap = (Map<String, String>) parameterContext
		.getParameterValue(2);
		Map<String, String> customParamMap = (Map<String, String>) parameterContext
		.getParameterValue(4);
		//准备ｊｅｘｌ表达式容器
		JexlContext context = JexlHelper.createContext();
		Map<String, String> values = context.getVars();
		if (customParamMap != null) {
			values.putAll(customParamMap);
		}
		if (workFlowParamMap != null) {
			values.putAll(workFlowParamMap);
		}
		ActivityInfo currentActivityInfo = (ActivityInfo) parameterContext
				.getParameterValue(5);
		// 取得活动的聚合模式
		String PolymeMode = currentActivityInfo.getPolymeMode();
		//单一聚合
		if (PolymeMode.equals(Constants.ACTIVITY_POLYMEMODE_SINGLE)) {
			IActivateActivity activateActivity = WorkFlowInstanceFactory.getActivateActivity(currentActivityInfo.getType());
			activateActivity.activate(parameterContext);
			//全部聚合
		} else if(PolymeMode.equals(Constants.ACTIVITY_POLYMEMODE_ALL)){
			    //包括路由在内的所有前驱节点都完成才可以激活
			if (WorkFlowTools.ifBeforeActivityAllFinish(workFlowInfo,
					workFlowInstance, currentActivityInfo, parameterContext.getConnection())) {
				IActivateActivity activateActivity = WorkFlowInstanceFactory.getActivateActivity(currentActivityInfo.getType());
				activateActivity.activate(parameterContext);
			}
			//多路聚合
		}else{
			    //1、除路由节点都要完成
			boolean isPass = false;
			boolean decisionIsPass=true;
			if (WorkFlowTools.ifBeforeActivityAllFinishWithoutDesition(workFlowInfo,
					workFlowInstance, currentActivityInfo, parameterContext.getConnection())) {
				//2、路由节点表达式都要为真
				ArrayList<ActivityInfo> decisionList = workFlowInfo.getBeforeActivityOnlyDecision(currentActivityInfo.getId());
				for(ActivityInfo activity:decisionList){
					DecisionInfo decision = (DecisionInfo)activity;
					List<IfInfo> ifList = decision.getIfinfos();
					for(IfInfo ifInfo :ifList){
						String expr = ifInfo.getExpr();
						String then = ifInfo.getThen();
						if(then.equals(currentActivityInfo.getId())){//找到需判断的那条路径
							if (WorkFlowTools.getExpValue(expr, context)) {
								//判断表达式为真的路径是否完成
								String process_instance_id = workFlowInstance.get("process_instance_id")
								+ "";
								if (WorkFlowTools.getActivityStateByPidAndAdefId(process_instance_id,
										decision.getId(), parameterContext.getConnection()) != Constants.ACTIVITY_STATE_FINISH) {
									decisionIsPass = false;
									break;
								/*ActivityInfo activityInfoP = workFlowInfo
								.getActivityInfoById(then);
								String activityDefId = activityInfoP.getId();
								String process_instance_id = workFlowInstance.get("process_instance_id")
								+ "";
								if (WorkFlowTools.getActivityStateByPidAndAdefId(process_instance_id,
										activityDefId, parameterContext.getConnection()) != Constants.ACTIVITY_STATE_FINISH) {
									break search;*/
								}
							}
						}
					}
					//条件为真的路由节点没有完成，退出循环
					if(decisionIsPass == false){
						break;
					}
				}
				if(decisionIsPass){
					isPass = true;
				}
			}
			if(isPass){
				IActivateActivity activateActivity = WorkFlowInstanceFactory.getActivateActivity(currentActivityInfo.getType());
				activateActivity.activate(parameterContext);
			}
			
		}
	}
	 /**
		 * 判断if表达式是真还是假
		 * 
		 * @param expr
		 * @return
		 */
		public static boolean getExpValue(String expr, JexlContext context) {

			boolean isRight = false;
			if (expr == null || expr.length() == 0) {
				isRight = false;
			} else {
				try {
					Object result = ExpressionFactory.createExpression(expr)
							.evaluate(context);

					if (result instanceof Boolean) {
						isRight = (Boolean) result;
					} else {
						isRight = false;
					}
				} catch (Exception e) {
				}
			}
			return isRight;
		}
	 /**
		 * 获得活动实例对象（为插入活动实例表用）用于激活活动
		 * 
		 * @param workFlowInstance
		 * @param activityInfo
		 * @param conn
		 * @return
		 * @throws SQLException
		 * @throws ParseException 
		 * @throws NumberFormatException 
		 */
		public static SaturnData getActivityInstance(SaturnData workFlowInstance,
				ActivityInfo activityInfo, Connection conn) throws Exception{
			String activityType = activityInfo.getType();
			String systemTime =Operation.baseService().GetSystemTime();
			SaturnData activityInstance = getActivityInstance();
			activityInstance.setString("name", activityInfo.getName()); 
			activityInstance
					.setString("description", activityInfo.getDescription()); 
			activityInstance.setString("type", activityInfo.getType()); 
			if (activityType.equals(Constants.ACTIVITY_TYPE_MAN)) {
				activityInstance.set("state", Constants.ACTIVITY_STATE_RUNNING); 
			} else if (activityType.equals(Constants.ACTIVITY_TYPE_AUTO)) {
				activityInstance.set("state", Constants.ACTIVITY_STATE_FINISH); 
				activityInstance.setString(
						"end_time", systemTime); 
			} else if (activityType.equals(Constants.ACTIVITY_TYPE_END)) {
				activityInstance.set("state", Constants.ACTIVITY_STATE_FINISH); 
				activityInstance.setString(
						"end_time", systemTime); 
			} else if (activityType.equals(Constants.ACTIVITY_TYPE_DECISION)) {
				activityInstance.set("state", Constants.ACTIVITY_STATE_FINISH); 
				activityInstance.setString(
						"end_time", systemTime); 
			}
			//TODO 子流程活动
			else if (activityType.equals(Constants.ACTIVITY_TYPE_SUB)) {
				activityInstance.set("state", Constants.ACTIVITY_STATE_RUNNING); 
			}

			activityInstance.set("priority", 80); 
			String limit_number = null;
			if (!activityType.equals(Constants.ACTIVITY_TYPE_END)
					&& !activityType.equals(Constants.ACTIVITY_TYPE_DECISION)) {
				 limit_number = activityInfo.getTimeLimit();
				// 流程的时间限制（取得开始活动中的时间限制）
				if (limit_number != null && !"".equals(limit_number)) { 
					activityInstance.set("limit_number", Integer 
							.parseInt(limit_number));
					activityInstance.set("final_time",WorkFlowTools.getTimeWithInterval(systemTime, Long.parseLong(limit_number)));
				} else {
					activityInstance.set("limit_number", 0); 
				}
			}
			activityInstance.setString("start_time", systemTime); 
			activityInstance.setString("activity_id", activityInfo.getId()); 
			activityInstance.set("process_instance_id", workFlowInstance 
					.get("process_instance_id")); 

			return activityInstance;
		}
}
